package org.urey.web3j;

import java.util.ArrayList;
import java.util.List;

import org.springframework.security.crypto.codec.Hex;
import org.web3j.abi.TypeEncoder;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.StaticArray;
import org.web3j.abi.datatypes.generated.Uint256;
import org.web3j.crypto.ECKeyPair;
import org.web3j.crypto.Hash;
import org.web3j.crypto.Sign;
import org.web3j.crypto.Sign.SignatureData;

public class Test {

	// 钱包私匙(对应的钱包地址为:0x5ebacac108d665819398e5c37e12b0162d781398)
	private static final String PRIVATE_KEY = "e62248374af86aa480f9cebd44f04cd02b915130d4fbda885a201488257b0a17";

	public static void main(String[] args) throws Exception {
		Uint256 num = new Uint256(11);

		List<Uint256> list = new ArrayList<Uint256>();
		list.add(new Uint256(2));
		list.add(new Uint256(8));
		list.add(new Uint256(555));
		StaticArray<Uint256> staticArray = new StaticArray<Uint256>(Uint256.class, list) {
		};

		Address address = new Address("0x6cd2Bf22B3CeaDfF6B8C226487265d81164396C5");

		StringBuilder msg = new StringBuilder();
		msg.append(TypeEncoder.encode(num));
		msg.append(TypeEncoder.encode(staticArray));

		msg.append(address.toString().substring(2, address.toString().length()));
		// System.out.println(TypeEncoder.encode(address));
		// 0000000000000000000000006cd2bf22b3ceadff6b8c226487265d81164396c5
		// 地址前面会补0，与solidity的abi.encodePacked不一致，
		System.out.println("msg:" + msg);

		byte[] bytes = Hex.decode(msg.toString());
		ECKeyPair keyPair = ECKeyPair.create(Hex.decode(PRIVATE_KEY));

		byte[] hash = Hash.sha3(bytes);
		System.out.println("hash:" + new String(Hex.encode(hash)));
		SignatureData signatureData = Sign.signMessage(hash, keyPair, false);
		// SignatureData signatureData = Sign.signMessage(bytes, keyPair);
		// 默认内部会再调用Hash.sha3

		String sign = "0x" + new String(Hex.encode(signatureData.getR())) + new String(Hex.encode(signatureData.getS())) + new String(Hex.encode(signatureData.getV()));
		System.out.println("sign:" + sign);
	}

}
